from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import os
from dotenv import load_dotenv

load_dotenv()

# PostgreSQL数据库配置
DATABASE_URL = os.getenv(
    "DATABASE_URL",
    "postgresql://nokia:nokia@localhost:5432/nokia"
)

# 创建数据库引擎
engine = create_engine(DATABASE_URL, pool_pre_ping=True)

# 创建会话工厂
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# 创建基类
Base = declarative_base()


# 数据库依赖项
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


# 配置管理类
class ConfigManager:
    """配置管理器，提供获取和管理系统配置的方法"""
    
    @staticmethod
    def get_config():
        """获取系统配置"""
        from models import SystemConfig
        db = SessionLocal()
        try:
            config = db.query(SystemConfig).first()
            if not config:
                # 如果配置不存在，创建默认配置
                config = SystemConfig(
                    avatar_prompt="",
                    internal_knowledge_id="",
                    internal_knowledge_api_key="",
                    external_knowledge_id="",
                    external_knowledge_api_key="",
                    ai_model_api_url="",
                    ai_model_name="",
                    ai_model_api_key="",
                    voice_config="",
                    floor_guide_image="",
                    video_resources=[]
                )
                db.add(config)
                db.commit()
                db.refresh(config)
            return config
        finally:
            db.close()
    
    @staticmethod
    def get_all_videos():
        """获取所有视频资源"""
        from models import SystemConfig
        from schemas import VideoResource
        db = SessionLocal()
        try:
            config = db.query(SystemConfig).first()
            if config and config.video_resources:
                # 将 JSON 数据转换为 VideoResource 对象
                return [VideoResource(**video) for video in config.video_resources]
            return []
        finally:
            db.close()
    
    @staticmethod
    def get_video_by_id(video_id: int):
        """根据ID获取视频资源"""
        from models import SystemConfig
        from schemas import VideoResource
        db = SessionLocal()
        try:
            config = db.query(SystemConfig).first()
            if config and config.video_resources:
                for video in config.video_resources:
                    if str(video.get('id')) == str(video_id):
                        return VideoResource(**video)
            return None
        finally:
            db.close()


# 创建全局配置管理器实例
db = ConfigManager()
